﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using ApplLogic.ApplClasses;
using ApplLogic.LogicalServices;
using ConnectionObjects;

namespace ApplLogic.Server
{
    public class ClientManagerComunicationHandler : ClientComunicationHandler
    {
        public ClientManagerComunicationHandler(TcpClient client ,int clientNumber, 
            ApplRequestHandlerAbstract applRequestHandler) :base(client, clientNumber, applRequestHandler)
        {}

        private ApplManagerRequestHandler downCast()
        {
            return m_ApplRequestHandler as ApplManagerRequestHandler;
        }

        protected override OutConnectionObject dealWithErrorInExecution()
        {
            OutConnectionObject returnObject = new OutConnectionObject();
            returnObject.ExceptionMessage = m_MethodExecuter.GetException().InnerException.Message;
            returnObject.OptionalMessage = string.Format("Manager mode: Error occured while executing {0} ",
                                                         m_MethodExecuter.MethodToExecute);
            return returnObject;
        }

        protected override OutConnectionObject dealWithCorrectExecution()
        {
            OutConnectionObject returnObject = new OutConnectionObject();
            if (m_MethodExecuter.HasReturnValue)
            {
                returnObject.RetVal = m_MethodExecuter.ReturnValue;
            }
            returnObject.ExceptionMessage = null;
            returnObject.OptionalMessage = string.Format("Manager mode: method {0} executed ok",
                                                         m_MethodExecuter.MethodToExecute);
            return returnObject;
        }

        protected override void executeRequest(InConnectionObject connectionObject)
        {
            m_MethodExecuter = new MethodExecuter(connectionObject.MethodToInvoke, connectionObject.InParameters, connectionObject.HasReturnValue);
            m_MethodExecuter.ExecuteMethod(downCast().GetType(), downCast());
        }
    }
}
